"""
合并相同name的location
遍历对象数组，将相同name的location合并
"""

# ==================== 方法1：使用字典分组合并 ====================

def merge_locations_method1(objects):
    """方法1：使用字典进行分组合并"""
    
    # 创建字典来分组相同name的对象
    grouped = {}
    
    for obj in objects:
        name = obj['name']
        location = obj['location']
        
        if name not in grouped:
            grouped[name] = {
                'name': name,
                'location': []  # 使用列表存储多个location
            }
        
        # 如果location不在列表中，则添加
        if location not in grouped[name]['location']:
            grouped[name]['location'].append(location)
    
    # 转换为结果列表
    result = list(grouped.values())
    
    # 将location列表转换为字符串（可选）
    for item in result:
        if isinstance(item['location'], list):
            item['location'] = ', '.join(item['location'])
    
    return result

# ==================== 方法2：使用defaultdict（更简洁） ====================

from collections import defaultdict

def merge_locations_method2(objects):
    """方法2：使用defaultdict简化代码"""
    
    grouped = defaultdict(list)
    
    for obj in objects:
        name = obj['name']
        location = obj['location']
        
        if location not in grouped[name]:
            grouped[name].append(location)
    
    # 构建结果
    result = []
    for name, locations in grouped.items():
        result.append({
            'name': name,
            'location': ', '.join(locations)  # 直接合并为字符串
        })
    
    return result

# ==================== 方法3：保持location为列表格式 ====================

def merge_locations_method3(objects):
    """方法3：保持location为列表格式"""
    
    grouped = defaultdict(list)
    
    for obj in objects:
        name = obj['name']
        location = obj['location']
        
        if location not in grouped[name]:
            grouped[name].append(location)
    
    # 保持列表格式
    result = []
    for name, locations in grouped.items():
        result.append({
            'name': name,
            'location': locations  # 保持为列表
        })
    
    return result

# ==================== 方法4：使用pandas（适合大数据量） ====================

def merge_locations_method4(objects):
    """方法4：使用pandas处理"""
    import pandas as pd
    
    # 转换为DataFrame
    df = pd.DataFrame(objects)
    
    # 分组并合并location
    result_df = df.groupby('name')['location'].apply(lambda x: ', '.join(set(x))).reset_index()
    
    # 转换回字典列表
    result = result_df.to_dict('records')
    
    return result

# ==================== 方法5：自定义合并规则 ====================

def merge_locations_custom(objects, separator=', '):
    """方法5：自定义合并规则"""
    
    grouped = defaultdict(list)
    
    for obj in objects:
        name = obj['name']
        location = obj['location']
        
        if location not in grouped[name]:
            grouped[name].append(location)
    
    # 自定义合并格式
    result = []
    for name, locations in grouped.items():
        result.append({
            'name': name,
            'location': separator.join(locations),
            'location_count': len(locations),  # 添加统计信息
            'locations_list': locations  # 保留原始列表
        })
    
    return result

# ==================== 测试数据 ====================

def create_test_data():
    """创建测试数据"""
    
    test_objects = [
        {'name': '张三', 'location': '北京'},
        {'name': '李四', 'location': '上海'},
        {'name': '张三', 'location': '广州'},
        {'name': '王五', 'location': '深圳'},
        {'name': '李四', 'location': '杭州'},
        {'name': '张三', 'location': '北京'},  # 重复的location
        {'name': '赵六', 'location': '成都'},
        {'name': '李四', 'location': '上海'},  # 重复的location
    ]
    
    return test_objects

# ==================== 演示和比较 ====================

def demonstrate_all_methods():
    """演示所有方法"""
    
    test_data = create_test_data()
    
    print("原始数据:")
    for i, obj in enumerate(test_data, 1):
        print(f"  {i}. {obj}")
    
    print("\n" + "="*60)
    
    # 方法1演示
    print("\n方法1 - 字典分组合并:")
    result1 = merge_locations_method1(test_data)
    for item in result1:
        print(f"  {item}")
    
    # 方法2演示
    print("\n方法2 - defaultdict合并:")
    result2 = merge_locations_method2(test_data)
    for item in result2:
        print(f"  {item}")
    
    # 方法3演示
    print("\n方法3 - 保持列表格式:")
    result3 = merge_locations_method3(test_data)
    for item in result3:
        print(f"  {item}")
    
    # 方法4演示
    print("\n方法4 - pandas处理:")
    result4 = merge_locations_method4(test_data)
    for item in result4:
        print(f"  {item}")
    
    # 方法5演示
    print("\n方法5 - 自定义合并规则:")
    result5 = merge_locations_custom(test_data, ' | ')
    for item in result5:
        print(f"  {item}")

# ==================== 实用函数 ====================

def merge_locations_simple(objects):
    """最简洁实用的合并函数"""
    
    result = {}
    for obj in objects:
        name = obj['name']
        location = obj['location']
        
        if name not in result:
            result[name] = {'name': name, 'location': set()}
        
        result[name]['location'].add(location)
    
    # 转换为列表并排序
    final_result = []
    for name, data in result.items():
        final_result.append({
            'name': name,
            'location': ', '.join(sorted(data['location']))
        })
    
    return final_result

def merge_with_duplicate_check(objects):
    """带重复检查的合并"""
    
    seen = set()
    grouped = {}
    
    for obj in objects:
        # 创建唯一标识符
        unique_id = f"{obj['name']}-{obj['location']}"
        
        # 检查是否重复
        if unique_id not in seen:
            seen.add(unique_id)
            
            if obj['name'] not in grouped:
                grouped[obj['name']] = []
            
            grouped[obj['name']].append(obj['location'])
    
    # 构建结果
    result = []
    for name, locations in grouped.items():
        result.append({
            'name': name,
            'location': ', '.join(locations),
            'location_count': len(locations)
        })
    
    return result

# ==================== 主程序 ====================

if __name__ == "__main__":
    print("🚀 合并相同name的location演示")
    print("="*60)
    
    # 演示所有方法
    demonstrate_all_methods()
    
    print("\n" + "="*60)
    print("💡 推荐使用方法:")
    
    test_data = create_test_data()
    
    # 最推荐的方法
    print("\n✅ 最简洁实用方法:")
    simple_result = merge_locations_simple(test_data)
    for item in simple_result:
        print(f"  {item}")
    
    print("\n✅ 带重复检查的方法:")
    duplicate_result = merge_with_duplicate_check(test_data)
    for item in duplicate_result:
        print(f"  {item}")
    
    print("\n🎯 方法选择建议:")
    print("  • 简单需求 → merge_locations_simple()")
    print("  • 需要去重 → merge_with_duplicate_check()")
    print("  • 大数据量 → merge_locations_method4() (pandas)")
    print("  • 自定义格式 → merge_locations_custom()")